package com.polaris.live.adapter

import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.util.ViewUtils
import com.polaris.live.resp.back_resp.BannerBean
import com.polaris.live.utils.image.loadImage
import com.polaris.live.utils.route.RouterUtils
import com.youth.banner.adapter.BannerAdapter

/**
 * banner适配器
 *
 * @author Created by 半仙 on 2023/10/13/013 9:53
 */
class ImageAdapter(
    data: MutableList<String>,
    private val isCropImage: Boolean = false,
) : BannerAdapter<String, ImageAdapter.BannerViewHolder>(data) {

    class BannerViewHolder(var imageView: ImageView) : RecyclerView.ViewHolder(imageView)

    override fun onCreateHolder(parent: ViewGroup, viewType: Int): BannerViewHolder {
        val imageView = ImageView(parent.context)
        imageView.layoutParams = ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        return BannerViewHolder(imageView)
    }

    override fun onBindView(holder: BannerViewHolder, data: String?, position: Int, size: Int) {
        val context = holder.imageView.context
        if (ViewUtils.isContextValid(context)) {
            Glide.with(context)
                .loadImage(data)
                .run {
                    if (isCropImage) {
                        centerCrop()
                    } else {
                        this
                    }
                }
                .into(holder.imageView)
        }
    }
}

class RouterImageAdapter(data: List<BannerBean>) :
    BannerAdapter<BannerBean, RouterImageAdapter.BannerViewHolder>(data) {

    override fun onCreateHolder(parent: ViewGroup, viewType: Int): BannerViewHolder {
        val imageView = ImageView(parent.context)
        imageView.layoutParams = ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        imageView.scaleType = ImageView.ScaleType.CENTER_CROP
        return BannerViewHolder(imageView)
    }

    override fun onBindView(holder: BannerViewHolder, data: BannerBean, position: Int, size: Int) {
        val context = holder.imageView.context
        if (ViewUtils.isContextValid(context)) {
            Glide.with(context)
                .loadImage(data.pic)
                .into(holder.imageView)
        }
        holder.imageView.setOnSingleClickListener {
            data.link?.ifEmpty {
                data.nativeLink?.ifEmpty { null }
            }?.let {
                RouterUtils.routerGoto(it)
            }
        }
    }

    class BannerViewHolder(val imageView: ImageView) : RecyclerView.ViewHolder(imageView)

}